class Node {
  constructor(val, next) {
    this.val = val;
    this.next = next;
  }
}

class LinkList {
  constructor() {
    this.dummy = new Node();
    this.tail = this.dummy;
    this.length = 0;
  }

  addAtTail(val) {
    const node = new Node(val);
    this.tail.next = node;
    this.tail = node;
    if (this.dummy === this.tail) {
      this.dummy.next = node
    }
    this.length += 1;
  }
  addAtHead(val) {
    const node = new Node(val);
    node.next = this.dummy.next;
    this.dummy.next = node;
    if (this.dummy === this.tail) {
      this.tail = node;
    }
    this.length += 1;
  }

  getPrevNode(index) {
    let front = this.dummy;
    let back = this.dummy.next;

    for (let i = 0; i < index && back !== null; i++) {
      front = back;
      back = back.next;
    }

    return front;
  }

  // index
  get(index) {
    if (index >= this.length || index < 0) return;
    return this.getPrevNode(index).next.val;
  }

  addAtIndex(val, index) {
    if (index <= 0) {
      return this.addAtHead(val);
    } else if (index === this.length) {
      return this.addAtTail(val);
    } else if (index > this.length) {
      return;
    }

    const node = new Node(val);
    const preNode = this.getPrevNode(index);
    node.next = preNode.next;
    preNode.next = node;
    this.length += 1;
  }
  deleteAtIndex(index) {
    if (index < 0 || index >= this.length) return;
    const node = this.getPrevNode(index);
    if (this.tail === node.next) {
      this.tail = node;
    }

    node.next = node.next.next;
    this.length -= 1;
  }

  findByVal(val) {
    for (let i = 0; i < this.length; i++) {
      const nodeVal = this.get(i);
      if (nodeVal === val) return true;
    }
    return false;
  }

  clear() {
    this.tail = new Node();
    this.dummy = this.tail;
    this.length = 0;
  }
}

const ll = new LinkList();

ll.addAtTail(0);
ll.addAtTail(1);
ll.addAtTail(2);
ll.addAtHead(-1);
ll.addAtIndex(3, 4);

// console.log(ll);

export { LinkList, Node };
